/*
* This file is a part of the open-eBackup project.
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* Copyright (c) [2024] Huawei Technologies Co.,Ltd.
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*/
#include "ReplicationDeviceManager.h"

using namespace nasreplicationservice;
using namespace Module;

ReplicationDeviceManager::ReplicationDeviceManager()
{}

ReplicationDeviceManager::~ReplicationDeviceManager()
{
    m_deviceMap.clear();
}

ReplicationDeviceManager& ReplicationDeviceManager::GetInstance()
{
    static ReplicationDeviceManager inst;
    return inst;
}

void ReplicationDeviceManager::AddDevice(std::string mgrIp, std::shared_ptr<DoradoNas> deviceControl)
{
    std::lock_guard<std::mutex> lk(m_mutex);
    m_deviceMap.emplace(mgrIp, deviceControl);
}

void ReplicationDeviceManager::RemoveDeviceFromMap(const std::string& mgrIp)
{
    std::lock_guard<std::mutex> lk(m_mutex);
    auto it = m_deviceMap.begin();
    it = m_deviceMap.find(mgrIp);
    if (it != m_deviceMap.end()) {
        m_deviceMap.erase(it);
    }
}

std::shared_ptr<DoradoNas> ReplicationDeviceManager::GetDeviceByIp(const std::string& mgrIp)
{
    std::lock_guard<std::mutex> lk(m_mutex);
    auto it = m_deviceMap.begin();
    it = m_deviceMap.find(mgrIp);
    if (it != m_deviceMap.end()) {
        return it->second;
    }
    return nullptr;
}

void ReplicationDeviceManager::Wait()
{
    m_semaphore.Wait();
}

void ReplicationDeviceManager::Signal()
{
    m_semaphore.Signal();
}